Together AI: LLM のファインチューニング
このノートブックは、Together AI プラットフォームを使用して大規模言語モデル(LLM)をファインチューニングするためのステップバイステップガイドです。データセットの準備から、新しいカスタムモデルでの推論呼び出しまで、ワークフロー全体をカバーします。
git add -A && git commit -m "Update project ($(date -u +'%Y-%m-%dT%H:%M:%SZ'))" && git push origin main💡 ファインチューニングの主要コンセプト
コードを書く前に、核心となるアイデアを把握しましょう。
ファインチューニング: 汎用的な事前学習済み LLM を取得し、より小さく特定のデータセットで追加トレーニングするプロセスです。これにより、モデルはカスタマーサポートチャットボットや特定のプログラミング言語のコードジェネレーターなど、特定のドメインやタスクに適応されます。
データセットのフォーマット: データの品質と形式が重要です。指示ベースのファインチューニングでは、明確なプロンプトと望ましい応答でデータを構造化する必要があります。Together AI は、各行が
"text"フィールドを含む JSON オブジェクトである JSONL 形式のデータを期待します。ベースモデル: 出発点となる事前学習済みモデルです。ベースモデルの選択は重要です。例えば、チャット用に事前学習されたモデルは、生のテキスト補完モデルよりもチャットボットの出発点として優れています。Together AI は、最先端のオープンソースモデルを多数提供しています。
ハイパーパラメーター: トレーニングジョブの設定であり、
learning_rate、batch_size、エポック数(モデルがデータセット全体を何回見るか)などがあります。これらを調整することで、モデルのパフォーマンスに大きく影響します。
⚙️ 1. セットアップとインストール
まず、必要な Python ライブラリをインストールする必要があります。
# Uncomment to install the required packages
# %pip install -U together datasets transformers python-dotenv -qAPI キーの読み込み
dotenv ライブラリを使用して、Together AI API キーを .env ファイルから安全に読み込みます。このノートブックと同じディレクトリに .env という名前のファイルを作成し、キーを追加してください。
TOGETHER_API_KEY="your-together-api-key-here"
import os
import together
from dotenv import load_dotenv
load_dotenv()
# Load API keys from environment variables
os.environ["TOGETHER_API_KEY"] = os.environ.get("TOGETHER_API_KEY", "")
os.environ["HUGGINGFACE_ACCESS_TOKEN"] = os.environ.get("HUGGINGFACE_ACCESS_TOKEN", "")
TOGETHER_API_KEY = os.environ.get("TOGETHER_API_KEY")
HUGGINGFACE_ACCESS_TOKEN = os.environ.get("HUGGINGFACE_ACCESS_TOKEN")📂 2. データの準備
databricks/databricks-dolly-15k データセットから小さなサンプルを使用します。これを、Llama のようなモデルでよく機能する標準的な指示テンプレート(<s>[INST]...[/INST]...</s>)を使用して、必要な JSONL 構造にフォーマットします。
import json
from datasets import load_dataset
# Load a sample of 500 examples from the dataset
dataset = load_dataset("databricks/databricks-dolly-15k", split="train", token=HUGGINGFACE_ACCESS_TOKEN).select(range(500))
def format_for_finetuning(example):
# Use a standard instruction format
return {"text": f"<s>[INST] {example['instruction']} [/INST] {example['response']} </s>"}
formatted_dataset = dataset.map(format_for_finetuning)
# Save the prepared data to a JSONL file (only the 'text' field per line)
file_name = "dolly_prepared.jsonl"
with open(file_name, 'w') as f:
for item in formatted_dataset:
f.write(json.dumps({"text": item["text"]}) + "\n")
print(f"Dataset prepared and saved to {file_name}")
print("--- Sample Entry ---")
with open(file_name, 'r') as f:
print(json.loads(f.readline())['text'])Dataset prepared and saved to dolly_prepared.jsonl --- Sample Entry --- <s>[INST] When did Virgin Australia start operating? [/INST] Virgin Australia commenced services on 31 August 2000 as Virgin Blue, with two aircraft on a single route. </s>
🚀 3. ファイルのアップロードとファインチューニングの開始
準備したデータセットをアップロードし、ファインチューニングジョブを起動します。togethercomputer/llama-2-7b-chat モデルをファインチューニングします。
# 1. Upload the training file
try:
upload_response = together.Files.upload(file=file_name)
training_file_id = upload_response['id']
print(f"File uploaded successfully. File ID: {training_file_id}")
# 2. Create the fine-tuning job
fine_tune_response = together.Finetune.create(
training_file=training_file_id,
model='togethercomputer/llama-2-7b-chat', # Base model to fine-tune
n_epochs=3, # Number of training epochs
n_checkpoints=1, # Number of checkpoints to save
batch_size=8, # Batch size
learning_rate=1e-5, # Learning rate
suffix='dolly-llama2-7b-tutorial', # A custom name for your fine-tuned model
)
print("\nFine-tuning job created:")
print(fine_tune_response)
except Exception as e:
print(f"Error uploading file or creating fine-tune job: {e}")/var/folders/pv/g_b0j0n53rz5fm8yrlw3jg040000gn/T/ipykernel_55499/1191766534.py:3: DeprecationWarning: Call to deprecated function upload. upload_response = together.Files.upload(file=file_name) Uploading file dolly_prepared.jsonl: 100%|██████████| 266k/266k [00:01<00:00, 212kB/s]
File uploaded successfully. File ID: file-9984a196-2c4b-4f82-b44e-da96665f34b1
/var/folders/pv/g_b0j0n53rz5fm8yrlw3jg040000gn/T/ipykernel_55499/1191766534.py:8: DeprecationWarning: Call to deprecated function create. fine_tune_response = together.Finetune.create(
Fine-tuning job created:
{'id': 'ft-91b93aa1-b4dd', 'training_file': 'file-9984a196-2c4b-4f82-b44e-da96665f34b1', 'model': 'togethercomputer/llama-2-7b-chat', 'n_epochs': 3, 'n_checkpoints': 1, 'n_evals': 0, 'batch_size': 8, 'learning_rate': 1e-05, 'lr_scheduler': {'lr_scheduler_type': 'cosine', 'lr_scheduler_args': {'min_lr_ratio': 0.0, 'num_cycles': 0.5}}, 'warmup_ratio': 0.0, 'max_grad_norm': 1.0, 'weight_decay': 0.0, 'eval_steps': 0, 'training_type': {'type': 'Lora'}, 'created_at': '2025-08-05T17:54:21.187Z', 'updated_at': '2025-08-05T17:54:21.187Z', 'status': <FinetuneJobStatus.STATUS_PENDING: 'pending'>, 'events': [], 'token_count': 0, 'total_price': 0, 'wandb_base_url': '', 'wandb_project_name': '', 'wandb_name': '', 'train_on_inputs': 'auto', 'suffix': 'dolly-llama2-7b-tutorial', 'training_method': {'method': 'sft', 'train_on_inputs': 'auto'}, 'random_seed': 'null', 'max_steps': -1, 'save_steps': 0, 'warmup_steps': 0, 'validation_split_ratio': 0, 'per_device_batch_size': 0, 'per_device_eval_batch_size': 0, 'gradient_accumulation_steps': 1, 'continued_checkpoint': '', 'merge_parent_adapter': False, 'parent_ft_id': '', 'try_byoa_upload': True, 'user_id': '68920bddaeed77e341146664', 'owner_address': '0xb8e99171f6536df47bc53657526b6dbdcfbc0ee9'}
🔎 4. ファインチューニングジョブの監視
ファインチューニングプロセスには時間がかかる場合があります。プログラムでステータスを監視できます。ジョブは queued、running、processing_files、最終的に completed の状態を経ます。
# Wait til the fine tuning finish (could take a while)
import time
job_id = "ft-338e34c5-fdc5"
status = together.Finetune.retrieve(fine_tune_id=job_id)
job_status = status.get('status', 'unknown')
print(f"Current job status: {job_status}")/var/folders/pv/g_b0j0n53rz5fm8yrlw3jg040000gn/T/ipykernel_55499/2545042428.py:5: DeprecationWarning: Call to deprecated function retrieve. status = together.Finetune.retrieve(fine_tune_id=job_id)
Current job status: completed
🤖 5. ファインチューニング済みモデルでの推論
ジョブが完了すると、モデルの準備は完了です!API から返された新しいモデル名を使用して推論を行います。トレーニングで使用したのと同じプロンプト形式([INST]...[/INST])を使用することを忘れないでください。
# This cell will only work if the monitoring step above has completed successfully.
# Get the fine-tuned model name from together fine tuning dashboard
dedicated_endpoint = 'https://api.together.ai/v1/inference/devon_a863/llama-2-7b-chat-dolly-llama2-7b-tutorial-e305d828' # FAKE dedicated endpoint for demonstration
import requests
headers = {
'Authorization': f'Bearer {os.environ.get("TOGETHER_API_KEY", "")}',
'Content-Type': 'application/json'
}
payload = {
"model": "devon_a863/llama-2-7b-chat-dolly-llama2-7b-tutorial-e305d828",
"prompt": "[INST] What is the secret to a successful startup? [/INST]",
"max_tokens": 256,
"temperature": 0.7,
"top_k": 50,
"top_p": 0.7,
"repetition_penalty": 1.1,
"stop": ["[/INST]", "</s>"]
}
try:
response = requests.post(dedicated_endpoint, headers=headers, json=payload)
response.raise_for_status()
print("\nFake Dedicated Endpoint Response:")
print(response.json())
except Exception as e:
print(e)まとめ
このノートブックは、Together AI プラットフォームを使用して大規模言語モデル(LLM)をファインチューニングする完全なワークフローを示しています。
- 主要コンセプト: ファインチューニング、データセットのフォーマット、ベースモデル、ハイパーパラメーターを紹介します。
- セットアップ: 必要なライブラリをインストールし、API キーを
.envファイルから安全に読み込みます。 - データ準備:
databricks/databricks-dolly-15kデータセットからサンプルをダウンロードし、指示ベースのファインチューニング用にフォーマットして JSONL ファイルとして保存します。 - ファイルのアップロードとファインチューニング: 準備したデータセットを Together AI にアップロードし、ベースモデル(
togethercomputer/llama-2-7b-chat)を使用してファインチューニングジョブを作成します。 - ジョブの監視: ファインチューニングジョブのステータスをプログラムで監視する方法を示します。
- 推論: ファインチューニング済みモデルを推論に使用する方法を示し、エラーハンドリングと(デモンストレーション用の)偽の専用エンドポイントの呼び出し方を含みます。
このノートブックは、Together AI 上で独自のデータを使用して LLM をカスタマイズするための実用的なエンドツーエンドガイドを提供し、堅牢なエラーハンドリングとトラブルシューティングのヒントも含んでいます。